const express = require('express');

let router = express.Router();

let db = require('../db/db');

let upload = require('../middleware/upload');

router.use('/list/:page?',(req,res)=>{
    res.locals.act = 'list';
    console.log(req.params.page);
    let page = req.params.page ? req.params.page : 0;
    let every = 2;
    let start = page*every;
    let pages,total;

    db.query('select count(*) as total from blog_article').then((data)=>{
        total = data[0].total;
        pages = Math.ceil(total/every);

        db.query(`select * from blog_article limit ${start},${every}`).then((data)=>{
            res.render('admin/article/index.ejs',{data:data,pages:pages,page:page});
        })
    })

})
router.get('/add',(req,res)=>{
    res.locals.act = 'add';
    res.render('admin/article/add.ejs',{});
})

router.post('/add',upload.single('avatar'),(req,res)=>{
    let POST = req.body;
    let post_time = parseInt(new Date().getTime()/1000);
    let avatar = '';
    if(req.file){
        let imgPath = '/uploads/'+req.file.filename;
        avatar = imgPath;
    }
    let sql = `insert into blog_article (title,content,post_time,avatar) values ('${POST.title}','${POST.content}','${post_time}','${avatar}')`;
    db.query(sql).then((data)=>{
        if(data.affectedRows){
            req.flash('success','添加成功');
            res.redirect('/article/list');
        }else{
            req.flash('error','操作失败');
            res.redirect('back');
        }
    })
})

router.get('/del/:aid',(req,res)=>{
    let aid = req.params.aid;
    let sql = `delete from blog_article where aid=${aid}`;
    db.query(sql).then((data)=>{
        if(data.affectedRows){
            req.flash('success','删除成功');
            res.redirect('/article/list');
        }else{
            req.flash('error','操作失败');
            res.redirect('back');
        }
    })
})

router.get('/edit/:aid',(req,res)=>{
    res.locals.act = '';
    let aid = req.params.aid;
    let sql = `select * from blog_article where aid=${aid}`;
    db.query(sql).then((data)=>{
        let nowData = data[0];
        res.render('admin/article/edit.ejs',nowData);
    })
})

router.post('/edit',upload.single('avatar'),(req,res)=>{
    res.locals.act = '';
    let aid = req.body.aid;
    let setImg='';
    if(req.file){
        let imgPath = '/uploads/'+req.file.filename;
        setImg = `,avatar='${imgPath}'`;
        console.log(setImg,'setImg');
    }
    let sql = `update blog_article  set title='${req.body.title}',content='${req.body.content}' ${setImg} where aid=${aid}`;
    console.log(sql,'sql');
    db.query(sql).then((data)=>{
        if(data.affectedRows){
            req.flash('success','更新成功');
            res.redirect('/article/list');
        }else{
            req.flash('error','更新失败');
            res.redirect('back');
        }
    })
})

module.exports = router;
